<!-- 角色列表页面 -->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <!-- 添加用户按钮 -->
      <el-row>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="addRolesDialogVisible = true"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table
        :data="roles"
        stripe
        border
      >
        <!-- 通过设置 type="expand" 和 Scoped slot 可以开启展开行功能，
      el-table-column 的模板会被渲染成为展开行的内容，展开行可访问的属
      性与使用自定义列模板时的 Scoped slot 相同。-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="[index1 == 0?'borderTop':'borderBottom','borderBottom','vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 == 0?'':'borderTop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3,index3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >
                      {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 主体区域 -->
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="300px"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="saveBeforeEditRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
    >
      <el-form
        :model="addRolesInfo"
        label-width="80px"
        :rules="addRolesInfoRules"
        ref="addRolesInfoRef"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="addRolesInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addRoles"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
    >
      <el-form
        :model="editRolesInfo"
        label-width="80px"
        :rules="editRolesInfoRules"
        ref="editRolesInfoRef"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="editRolesInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editRoles"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话页面 -->
    <el-dialog
      title="分配权限"
      :visible.sync="assignRightdialogVisible"
      width="50%"
    >
      <!-- tree控件 -->
      <el-tree
        :data="rightsList"
        :props="rightProps"
        node-key="id"
        show-checkbox
        ref="treeRef"
        :default-checked-keys='defkeys'
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="assignRightdialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="setRight"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      roles: [],
      // 控制添加角色对话框的显示与隐藏
      addRolesDialogVisible: false,
      // 控制修改角色对话框的显示与隐藏
      editRolesDialogVisible: false,
      // 添加角色的信息
      addRolesInfo: {
        roleName: "",
        roleDesc: "",
      },
      // 编辑角色的信息
      editRolesInfo: {
        rolePermissionDesc: "1",
      },
      //校验添加角色表单
      addRolesInfoRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 校验修改角色表单
      editRolesInfoRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 控制分配权限对话框的显示与隐藏
      assignRightdialogVisible: false,
      // 权限列表
      rightsList: [],
      // tree的展开方式
      rightProps: {
        children: "children",
        label: "authName",
      },
      // tree默认展示的叶子
      defkeys: [],
      // 当前选中的角色id
      roldId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色裂变失败!");
      this.roles = res.data;
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesInfoRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请正确填入信息！");
        const { data: res } = await this.$http.post("roles", this.addRolesInfo);
        if (res.meta.status !== 201)
          return this.$message.error("添加角色失败！");
        this.$message.success("添加角色成功！");
        this.getRolesList();
        this.addRolesDialogVisible = false;
      });
    },
    // 删除角色
    deleteRoles(id) {
      this.$confirm("此操作将永久删除该用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) return this.$message.error("删除失败！");
          this.getRolesList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑角色信息
    // 先通过当前列的id从数据库中获取其信息并保存
    async saveBeforeEditRoles(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色信息失败！");
      this.editRolesInfo = res.data;
      this.editRolesDialogVisible = true;
    },
    editRoles() {
      this.$refs.editRolesInfoRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入正确的信息！");
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesInfo.roleId}`,
          {
            roleName: this.editRolesInfo.roleName,
            roleDesc: this.editRolesInfo.roleDesc,
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("修改信息失败！");
        this.$message.success("修改信息成功！");
        this.getRolesList();
        this.editRolesDialogVisible = false;
      });
    },
    // 删除角色的权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) return this.$message.error("删除失败！");
          // 使用this.getRolesList()函数会造成页面重新渲染，不建议使用
          // this.getRolesList();
          // res返回的是当前角色最新的权限，故只需重新赋值即可
          role.children = res.data;
          this.$message.success("删除成功！");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展示设置角色权限对话框
    async showSetRightDialog(role) {
      // 保存当前角色id 以便确定时找到该参数
      this.roleId = role.id;
      // 请求权限树
      const { data: res } = await this.$http.get(`rights/tree`);
      if (res.meta.status !== 200)
        return this.$message.error("请求权限列表失败！");
      this.rightsList = res.data;
      // 使用递归获取叶子的id
      this.defkeys = [];
      this.getLeafKeys(role, this.defkeys);
      this.assignRightdialogVisible = true;
    },
    // 递归的获取角色先所有三级权限的id，并保存到数组中
    getLeafKeys(node, arr) {
      // 如果是叶子 则将id加入到arr中
      if (!node.children) {
        return arr.push(node.id);
      }
      // 如果不是叶子 则继续递归
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 为角色分配权限
    async setRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const keysStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keysStr }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败！");
      this.$message.success("分配权限成功!");
      this.getRolesList();
      this.assignRightdialogVisible = false;
    },
  },
};
</script>

<style  scoped>
.cell {
  font-size: 12px;
}

.el-tag {
  margin: 7px;
}

/* 顶部加边线 */
.borderTop {
  border-top: 1px solid #eee;
}

/* 底部加边线 */
.borderBottom {
  border-bottom: 1px solid #eee;
}

/* 垂直居中 */
.vcenter {
  display: flex;
  align-items: center;
}
</style>
